<?php

namespace Biz\service\BrandRights;

use Biz\model\brand\BrandPackage;
use Biz\model\brandPack\BrandPackageRightsLog;
use Biz\model\brandRights\BrandRightsSource;
use Biz\pockets\constInterface\SourceRightsInterface;
use Biz\service\brandPack\BrandPackageRightsLogService;
use Doraemon\pockets\datebase\BaseDbModel;
use Biz\model\brandRights\BrandPackageRightsConfig;

class BrandPackageRightsConfigService
{

    public static function getCount()
    {
        $where['status'] = BaseDbModel::STATUS_NORMAL;
        $where['GROUP'] = "package_id";
        BrandPackageRightsConfig::selectCount($where);
    }

    /**
     * 审核操作
     *
     * @param $params
     *
     * @return bool
     */
    public static function audit($params): bool
    {
        $where['id'] = $params['id'];
        $data['data_status'] = $params['data_status'];
        $data['admin_id'] = $params['admin_id'];
        BrandPackageRightsConfig::updateData($data, $where);
        return true;
    }

    /**
     * 获取套餐权益列表
     * @param $id
     * @param array $rightsWhere
     * @return array
     */
    public static function getPackConfigList($id, array $rightsWhere = []): array
    {
        $data = [
            'pack_info' => [],
            'sources_list' => [],
        ];
        //套餐信息
        $wherePack['package_status'] = [BrandPackage::STATUS_NORMAL, BrandPackage::STATUS_OFF];
        $wherePack['id'] = $id;
        $fieldPack = [
            "id",
            "package_name",
            "meal_time",
            "price",
            "discount_price",
            //            "pack_type"
        ];
        //套餐信息
        $packInfo = BrandPackage::getInfoByWhere($wherePack, $fieldPack);
        if (!$packInfo) {
            return $data;
        }
        $data['pack_info'] = $packInfo;
        $where['package_id'] = $id;

        $where['status'] = BrandPackageRightsConfig::STATUS_NORMAL;

        $field = ['rights_source_id', 'rights_data', 'status'];

        //已拥有权益
        $ownSource = BrandPackageRightsConfig::selectList($where, $field);
        $ownSource = array_column($ownSource, null, 'rights_source_id');
//        $list['rights_source_ids'] = $rightsSourceIds ?: [];

        //获取所有权益
        if (isset($rightsWhere['data_status'])) {
            if ($rightsWhere['data_status'] == BaseDbModel::STATUS_NORMAL && !empty($ownSource)) {
                $rightsWhere['id'] = array_column($ownSource, 'rights_source_id');
            } elseif (!empty($ownSource)) {
                $rightsWhere['id[!]'] = array_column($ownSource, 'rights_source_id');
            }
        }
        $rightsWhere['data_status'] = BrandRightsSource::STATUS_NORMAL;
        $rightsWhere['ORDER'] = [
            'sort_weight' => 'ASC',
        ];
        $sourcesList = BrandRightsSourceService::getList($rightsWhere);
        foreach ($sourcesList as $key => $item) {
            $sourcesList[$key]['is_checked'] = 0;
            $sourcesList[$key]['rights_data'] = 0;
            if (isset($ownSource[$item['id']]) && $ownSource[$item['id']]['rights_data'] >= 1) {
                $sourcesList[$key]['is_checked'] = 1;
                $sourcesList[$key]['rights_data'] = $ownSource[$item['id']]['rights_data'];
            }
            $sourcesList[$key]['package_id'] = $id;
            $sourcesList[$key]['status'] = $ownSource[$item['id']]['status'];
        }

        $data['sources_list'] = $sourcesList;
        //获取基础权益id
        return $data;
    }

    /**
     * 套餐权益行内数据修改
     * @param $pickId
     * @param $sourceId
     * @param $params
     * @param $adminId
     * @return bool
     * @throws \Exception
     */
    public static function updatePackSource($pickId, $sourceId, $params, $adminId = 0)
    {
        $result = false;
        if (isset($params['status'])) {
            $result = self::updatePackSourceRightsStatus($pickId, $sourceId, $params, $adminId);
        } elseif (isset($params['value'])) {
            $result = self::updatePackSourceRightsCount($pickId, $sourceId, $params, $adminId);
        }
        return $result;
    }

    /**
     * 更新消耗型权益数量
     * @param $pickId
     * @param $rightsSourceId
     * @param $params
     * @param $adminId
     * @param $firstOpen
     * @return bool
     * @throws \Exception
     */
    public static function updatePackSourceRightsCount($pickId, $rightsSourceId, $params, $adminId, $firstOpen = false)
    {
        if (!isset($params['value'])) {
            throw new \Exception("参数错误");
        }
        $sourceInfo = BrandRightsSourceService::getListById($rightsSourceId);
        if (!$sourceInfo) {
            throw new \Exception("该权益不存在，请刷新");
        }

        $brandPackage = BrandPackage::getById($pickId);
        if (!$brandPackage || empty($brandPackage)) {
            throw new \Exception('套餐不存在');
        }

        //查询套餐id
        $where['package_id'] = $pickId;
        $where['rights_source_id'] = $rightsSourceId;
        $where['status'] = BrandPackageRightsConfig::STATUS_NORMAL;
        $result = BrandPackageRightsConfig::getInfo($where);
        $packageRightsConfig = [];
        if ($result && is_array($result)) {
            $packageRightsConfig = $result;
        }
        if (empty($packageRightsConfig)) {
            throw new \Exception("先开启该权益，再设置数量");
        }
        $data = [];
        $rightsData = $params['value'] ?? 0;
        $data['rights_data'] = $rightsData;
        $updateWhere = [
            'id' => $packageRightsConfig['id'],
            'rights_data' => $packageRightsConfig['rights_data'],
        ];
        BrandPackageRightsConfig::updateData($data, $updateWhere);

        self::updatePackagePrice($pickId);

        if (!$firstOpen) {
            BrandPackageRightsLogService::record(
                $pickId,
                $rightsSourceId,
                BrandPackageRightsLog::TYPE_CHANGE_RIGHTS_NUM,
                $adminId,
                $rightsData
            );
        }

        return true;
    }

    /**
     * 开启关闭套餐权益
     * @param $pickId
     * @param $sourceId
     * @param $params
     * @param $adminId
     * @return bool
     * @throws \Exception
     */
    public static function updatePackSourceRightsStatus($pickId, $rightsSourceId, $params, $adminId)
    {
        if (!isset($params['status'])) {
            throw new \Exception("参数异常");
        }

        $sourceInfo = BrandRightsSourceService::getListById($rightsSourceId);
        if (!$sourceInfo) {
            throw new \Exception("该权益不存在或未开启，请刷新");
        }

        $brandPackage = BrandPackage::getById($pickId);
        if (!$brandPackage || empty($brandPackage)) {
            throw new \Exception('套餐不存在');
        }

        //查询套餐id
        $where['package_id'] = $pickId;
        $where['rights_source_id'] = $rightsSourceId;
        $where['status'] = BrandPackageRightsConfig::STATUS_ON;
        $brandPackageRightsConfig = BrandPackageRightsConfig::getInfo($where, ['id', 'rights_data']);
        $id = null;
        $rights_data = 0;
        if ($brandPackageRightsConfig && is_array($brandPackageRightsConfig)) {
            $id = $brandPackageRightsConfig['id'];
            $rights_data = $brandPackageRightsConfig['rights_data'];
        }

        $switchStatus = $params['status'] == BrandPackageRightsConfig::STATUS_ON;

        //套餐开启权益
        if ($switchStatus) {
            $count = 0;
            if (!$id) {
                $data['package_id'] = $pickId;
                $data['rights_source_id'] = $sourceInfo['id'];
                $data['status'] = BrandPackageRightsConfig::STATUS_ON;
                BrandPackageRightsConfig::insertData($data);
                if ($sourceInfo['rights_type'] == BrandRightsSource::RIGHTS_TYPE_LIMIT_NUM ||
                    $sourceInfo['rights_type'] == BrandRightsSource::RIGHTS_TYPE_NUM) {
                    //开启消耗型和数量型默认给1
                    $count = 1;
                    self::updatePackSourceRightsCount($pickId, $sourceInfo['id'], ['value' => $count], $adminId, true);
                }
                BrandPackageRightsLogService::record($pickId, $sourceInfo['id'], BrandPackageRightsLog::TYPE_ADD,
                    $adminId, $count);
                self::updatePackagePrice($pickId);
            }
            return true;
        }

        //套餐取消权益
        if ($id) {
            $deleteWhere['id'] = $id;
            BrandPackageRightsConfig::deleteData($deleteWhere);
            BrandPackageRightsLogService::record($pickId, $sourceInfo['id'], BrandPackageRightsLog::TYPE_CLOSE,
                $adminId);
            self::updatePackagePrice($pickId);
            return true;
        }
        return false;
    }

    /**
     * 更新套餐价格
     */
    public static function updatePackagePrice($packageId)
    {
        $packagesPrice = self::getPackagesPrice([$packageId]);
        $packagePrice = 0.00;
        if (isset($packagesPrice[$packageId])) {
            $packagePrice = $packagesPrice[$packageId]['amount'] ?? 0.00;
        }
        $data['cal_price'] = $packagePrice;
        $where['id'] = $packageId;
        BrandPackage::updateData($data, $where);
        return $packagePrice;
    }


    //获取一个套餐已配置的权益
    public static function getOnePackageRightsConfigs($packId)
    {
        $where['package_id'] = $packId;
        $where['status'] = BrandPackageRightsConfig::STATUS_NORMAL;
        $packageRights = [];
        $result = BrandPackageRightsConfig::selectList($where);
        if ($result && is_array($result)) {
            $packageRights = $result;
        }
        return $packageRights;
    }

    //获取多个套餐金额
    public static function getPackagesPrice($packageIds)
    {
        $where['package_id'] = $packageIds;
        $where['status'] = BaseDbModel::STATUS_NORMAL;
        $packageRights = [];
        $result = BrandPackageRightsConfig::selectList($where);
        if ($result && is_array($result)) {
            $packageRights = $result;
        }
        $sourceRightsMap = BrandRightsSourceService::getRightsSourceMap([]);
        $amountMap = [];
        foreach ($packageRights as $packageRight) {
            $packId = $packageRight['package_id'];
            if (!isset($amountMap[$packId]['amount'])) {
                $amountMap[$packId]['amount'] = 0.00;
            }
            $rightsName = $sourceRightsMap[$packageRight['rights_source_id']]['rights_name'];
            $rightsPrice = $sourceRightsMap[$packageRight['rights_source_id']]['price'];
            $rightsType = $sourceRightsMap[$packageRight['rights_source_id']]['rights_type'];
            $count = 1;
            if ($rightsType == BrandRightsSource::RIGHTS_TYPE_LIMIT_NUM || $rightsType == BrandRightsSource::RIGHTS_TYPE_NUM) {
                $count = intval($packageRight['rights_data']);
            }
            if ($rightsName == SourceRightsInterface::CONTENT_RECEIVE && $count == SourceRightsInterface::COUNT_UNLIMIT) {
                $count = 1;
                $rightsPrice = 2000.00;
            }
            $amountMap[$packId]['amount'] += $count * $rightsPrice;
        }
        return $amountMap;
    }

}